<template>
  <el-dialog :title="`为用户更改权限${user?' - '+user.userName+' - '+user.name:''}`" :visible.sync="dialogVisible" width="40%" :close-on-click-modal="false">
    <el-alert v-if="!(user && user.id)" title="请选择正确的用户" type="error" effect="dark"></el-alert>
    <div style="overflow-x: hidden;">
      <ul v-if="user && user.id" id="treePermissionsForUser" style="height:320px;" class="ztree ztreeMd"></ul>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close()">取消</el-button>
      <el-button type="primary" :loading="isSubmitLoading" @click="save()">保存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getUserPermissions, updateUserPermissions } from "@/api/permisson";
import $ from "@/vendor/jquery";
import "ztree";
import "@/assets/ztree-bootstrap/ztree-bootstrap-style.scss";

export default {
  data() {
    return {
      user: undefined,
      dialogVisible: false,
      isSubmitLoading: false,
      setting: {
        view: {
          showIcon: false,
          nameIsHTML: true
        },
        check: {
          enable: true,
          chkboxType: { Y: "ps", N: "ps" }
        },
        data: {
          simpleData: {
            enable: true
          }
        },
        callback: {
          onClick: this.zTreeOnClick,
          onRightClick: this.zTreeOnRightClick
        }
      }
    };
  },
  methods: {
    show(user) {
      this.user = user;
      const userId = user && user.id;
      $.fn.zTree.init($("#treePermissionsForUser"), this.setting, []); // 先清空树
      this.dialogVisible = true;
      if (userId) {
        const zNodes = [];
        getUserPermissions(userId).then(result => {
          var content_type_list = []
          var model_list = []
          result.forEach(p => {
            if (content_type_list.indexOf(`content_type_list_${p.content_type_app_label}`) === -1) {
              content_type_list.push(`content_type_list_${p.content_type_app_label}`)
              var is_checked1 = result.find(item => item.content_type_app_label === p.content_type_app_label && p.is_granted === false) === undefined;
              zNodes.push({
                id: `content_type_list_${p.content_type_app_label}`,
                pId: null,
                // name: `<strong style="color:red;">----- ${p.content_type_app_label} -----</strong>`,
                name: p.content_type_app_label,
                open: true,
                checked: is_checked1
              });
            }
            if (model_list.indexOf(`model_${p.content_type_id}`) === -1) {
              model_list.push(`model_${p.content_type_id}`)
              var is_checked2 = result.find(item => item.content_type_id === p.content_type_id && p.is_granted === false) === undefined;
              zNodes.push({
                id: `model_${p.content_type_id}`,
                pId: `content_type_list_${p.content_type_app_label}`,
                name: p.content_type_name,
                open: false,
                checked: is_checked2
              });
            }

            zNodes.push({
              id: p.id,
              pId: `model_${p.content_type_id}`,
              name: p.name,
              open: false,
              checked: p.is_granted,
              is_data: true
            });
          });
          $.fn.zTree.init($("#treePermissionsForUser"), this.setting, zNodes);
        });
      }
    },
    save() {
      this.isSubmitLoading = true;
      const treeObj = $.fn.zTree.getZTreeObj("treePermissionsForUser");
      const checkedNodes = treeObj.getCheckedNodes(true);
      // const unCheckedNodes = treeObj.getCheckedNodes(false);
      const input = {
        permission_ids: [
          ...checkedNodes.filter(item => item.is_data).map(item => { return item.id })
        ]
      };

      updateUserPermissions(this.user.id, input)
        .then(() => {
          this.$message({ message: "操作成功", type: "success" });
          this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
          this.close();
        })
        .finally(() => {
          this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
        });
    },
    close() {
      this.dialogVisible = false;
      this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
    },
    zTreeOnClick(event, treeId, treeNode) {
      if (!treeNode) {
        return;
      }
      const treeObj = $.fn.zTree.getZTreeObj(treeId);
      treeObj.expandNode(treeNode);
    },

    zTreeOnRightClick(event, treeId, treeNode) {
      if (!treeNode) {
        return;
      }
      const treeObj = $.fn.zTree.getZTreeObj(treeId);
      treeObj.checkNode(treeNode, !treeNode.checked, true);
    }
  }
};
</script>
